package net.oschina.kjtang.qywx.api.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import net.oschina.kjtang.qywx.api.entity.User;
import net.oschina.kjtang.qywx.api.service.WxUserService;
import net.oschina.kjtang.qywx.common.component.httpclient.HttpClientComponent;
import net.oschina.kjtang.qywx.common.component.httpclient.HttpResult;
import net.oschina.kjtang.qywx.common.constants.RCodeConstants;
import net.oschina.kjtang.qywx.common.constants.WxAPIConstants;
import net.oschina.kjtang.qywx.common.exception.RCodeException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by kaijun on 2017/12/2.
 */
@Service
public class WxUserServiceImpl implements WxUserService{

    private Logger logger = LoggerFactory.getLogger(WxUserServiceImpl.class);

    @Autowired
    private HttpClientComponent httpClientComponent;

    @Override
    public void addUser(User user,String accessToken) throws RCodeException {
        try{
            String userJson = JSON.toJSONString(user);
            HttpResult httpResult = httpClientComponent.doPostJson(WxAPIConstants.USER_CREATE_URL.replace("ACCESS_TOKEN",accessToken),userJson);
            if(httpResult.getStatus()==200){
                JSONObject jsonObject = JSON.parseObject(httpResult.getData());
                if(jsonObject!=null){
                    int errcode = jsonObject.getIntValue("errcode");
                    String errmsg = jsonObject.getString("errmsg");
                    if(errcode!=0){
                        logger.info("[新增用户]", "addUser response:{}", new Object[]{jsonObject.toJSONString()});
                        throw  new RCodeException(errcode,new RuntimeException(errmsg));
                    }
                }else{
                    throw  new RCodeException(RCodeConstants.FAIL,new RuntimeException("新增用户失败"));
                }
            }
        }catch (Exception e){
            throw  new RCodeException(RCodeConstants.FAIL,e);
        }
    }

    @Override
    public void updateUser(User user, String accessToken) throws RCodeException {
        try{
            String userJson = JSON.toJSONString(user);
            HttpResult httpResult = httpClientComponent.doPostJson(WxAPIConstants.USER_UPDATE_URL.replace("ACCESS_TOKEN",accessToken),userJson);
            if(httpResult.getStatus()==200){
                JSONObject jsonObject = JSON.parseObject(httpResult.getData());
                if(jsonObject!=null){
                    int errcode = jsonObject.getIntValue("errcode");
                    String errmsg = jsonObject.getString("errmsg");
                    if(errcode!=0){
                        logger.info("[修改用户]", "addUser response:{}", new Object[]{jsonObject.toJSONString()});
                        throw  new RCodeException(errcode,new RuntimeException(errmsg));
                    }
                }else{
                    throw  new RCodeException(RCodeConstants.FAIL,new RuntimeException("修改用户失败"));
                }
            }
        }catch (Exception e){
            throw  new RCodeException(RCodeConstants.FAIL,e);
        }
    }

    @Override
    public void deleteUser(String userid,String accessToken) throws RCodeException {
        try{
            HttpResult httpResult = httpClientComponent.doGet(WxAPIConstants.USER_DELETE_URL.replace("ACCESS_TOKEN",accessToken).replace("USERID",userid));
            if(httpResult.getStatus()==200){
                JSONObject jsonObject = JSON.parseObject(httpResult.getData());
                if(jsonObject!=null){
                    int errcode = jsonObject.getIntValue("errcode");
                    String errmsg = jsonObject.getString("errmsg");
                    if(errcode!=0){
                        logger.info("[批量删除用户]", "addUser response:{}", new Object[]{jsonObject.toJSONString()});
                        throw  new RCodeException(errcode,new RuntimeException(errmsg));
                    }
                }else{
                    throw  new RCodeException(RCodeConstants.FAIL,new RuntimeException("批量删除用户失败"));
                }
            }
        }catch (Exception e){
            throw  new RCodeException(RCodeConstants.FAIL,e);
        }
    }

    @Override
    public void batchDeleteUser(List<String> userids,String accessToken) throws RCodeException {
        try{
            Map mapData = new HashMap<>();
            mapData.put("useridlist",userids);
            String jsonData = JSON.toJSONString(mapData);
            HttpResult httpResult = httpClientComponent.doPostJson(WxAPIConstants.USER_BATCH_DELETE_URL.replace("ACCESS_TOKEN",accessToken),jsonData);
            if(httpResult.getStatus()==200){
                JSONObject jsonObject = JSON.parseObject(httpResult.getData());
                if(jsonObject!=null){
                    int errcode = jsonObject.getIntValue("errcode");
                    String errmsg = jsonObject.getString("errmsg");
                    if(errcode!=0){
                        logger.info("[删除用户]", "addUser response:{}", new Object[]{jsonObject.toJSONString()});
                        throw  new RCodeException(errcode,new RuntimeException(errmsg));
                    }
                }else{
                    throw  new RCodeException(RCodeConstants.FAIL,new RuntimeException("删除用户失败"));
                }
            }
        }catch (Exception e){
            throw  new RCodeException(RCodeConstants.FAIL,e);
        }
    }

    @Override
    public User getUser(String userid, String accessToken) throws RCodeException {
        User user = null;
        try{
            HttpResult httpResult = httpClientComponent.doGet(WxAPIConstants.USER_GET_URL.replace("ACCESS_TOKEN",accessToken).replace("USERID",userid));
            if(httpResult.getStatus()==200){
                System.out.println(httpResult.getData());
                JSONObject jsonObject = JSON.parseObject(httpResult.getData());
                if(jsonObject!=null){
                    int errcode = jsonObject.getIntValue("errcode");
                    String errmsg = jsonObject.getString("errmsg");
                    if(errcode!=0){
                        logger.info("[查询用户]", "addUser response:{}", new Object[]{jsonObject.toJSONString()});
                        throw  new RCodeException(errcode,new RuntimeException(errmsg));
                    }else{
                        user = JSON.parseObject(httpResult.getData(),User.class);
                    }
                }else{
                    throw  new RCodeException(RCodeConstants.FAIL,new RuntimeException("新增用户失败"));
                }
            }
        }catch (Exception e){
            throw  new RCodeException(RCodeConstants.FAIL,e);
        }
        return user;
    }

    @Override
    public List<User> getDepartmentUserList(String departId, boolean isFetchChild, String accessToken) throws RCodeException {
        List<User> userlist = new ArrayList<>();
        try{
            HttpResult httpResult = httpClientComponent.doGet(WxAPIConstants.USER_DEPARTMENT_LIST_URL.replace("ACCESS_TOKEN",accessToken).replace("DEPARTMENT_ID",departId).replace("FETCH_CHILD",isFetchChild?"1":"0"));
            if(httpResult.getStatus()==200){
                System.out.println(httpResult.getData());
                JSONObject jsonObject = JSON.parseObject(httpResult.getData());
                if(jsonObject!=null){
                    int errcode = jsonObject.getIntValue("errcode");
                    String errmsg = jsonObject.getString("errmsg");
                    if(errcode!=0){
                        logger.info("[查询部门用户]", "addUser response:{}", new Object[]{jsonObject.toJSONString()});
                        throw  new RCodeException(errcode,new RuntimeException(errmsg));
                    }else{
                        userlist = JSON.parseObject(jsonObject.getString("userlist"),userlist.getClass());
                    }
                }else{
                    throw  new RCodeException(RCodeConstants.FAIL,new RuntimeException("查询部门用户失败"));
                }
            }
        }catch (Exception e){
            throw  new RCodeException(RCodeConstants.FAIL,e);
        }
        return userlist;
    }

    @Override
    public List<User> getDepartmentUserDetail(String departId, boolean isFetchChild, String accessToken) throws RCodeException {
        List<User> userlist = new ArrayList<>();
        try{
            HttpResult httpResult = httpClientComponent.doGet(WxAPIConstants.USER_DEPARTMENT_USER_URL.replace("ACCESS_TOKEN",accessToken).replace("DEPARTMENT_ID",departId).replace("FETCH_CHILD",isFetchChild?"1":"0"));
            if(httpResult.getStatus()==200){
                System.out.println(httpResult.getData());
                JSONObject jsonObject = JSON.parseObject(httpResult.getData());
                if(jsonObject!=null){
                    int errcode = jsonObject.getIntValue("errcode");
                    String errmsg = jsonObject.getString("errmsg");
                    if(errcode!=0){
                        logger.info("[查询部门用户详细]", "addUser response:{}", new Object[]{jsonObject.toJSONString()});
                        throw  new RCodeException(errcode,new RuntimeException(errmsg));
                    }else{
                        userlist = JSON.parseObject(jsonObject.getString("userlist"),userlist.getClass());
                    }
                }else{
                    throw  new RCodeException(RCodeConstants.FAIL,new RuntimeException("查询部门用户详细失败"));
                }
            }
        }catch (Exception e){
            throw  new RCodeException(RCodeConstants.FAIL,e);
        }
        return userlist;
    }
}
